package com.czg.jsonschema2lombokpojo.rules;

import java.util.Iterator;

import com.czg.jsonschema2lombokpojo.Schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.sun.codemodel.JDefinedClass;

/**
 * 应用“属性”schema规则。
 *
 */
public class PropertiesRule implements Rule<JDefinedClass, JDefinedClass> {

    private final RuleFactory ruleFactory;

    protected PropertiesRule(RuleFactory ruleFactory) {
        this.ruleFactory = ruleFactory;
    }

    /**
     * 应用此schema规则执行所需的代码生成步骤。
     * <p>
     * 对于属性节点中存在的每个属性，该规则将调用给定schema映射器提供的“property”规则。
     *
     * @param nodeName
     *            要为其添加属性的节点的名称
     * @param node
     *            属性节点，包含属性名称及其定义
     * @param jclass
     *            将添加给定属性的Java类型
     * @return 给定的jclass
     */
    @Override
    public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema schema) {
        if (node == null) {
            node = JsonNodeFactory.instance.objectNode();
        }

        for (Iterator<String> properties = node.fieldNames(); properties.hasNext(); ) {
            String property = properties.next();

            ruleFactory.getPropertyRule().apply(property, node.get(property), node, jclass, schema);
        }
        return jclass;
    }
}
